package com.wxg.algorithm.chapter02.comparable;

import com.wxg.algorithm.chapter02.entity.Student;
import com.wxg.algorithm.common.ISort;

import java.util.Arrays;

/**
 * 选择排序
 *
 * @param <T>
 */
public class SelectionSort<T extends Comparable> implements ISort<T> {

    public static void main(String[] args) {
        SelectionSort ss = new SelectionSort();
        Integer[] arr = {2, 1, 8, 3, 5, 4, 6, 7};

        System.out.println(Arrays.toString(arr));

        ss.sort(arr);

        System.out.println(Arrays.toString(arr));

        // float

        Float[] arr2 = {2.1f, 1f, 8f, 3f, 5f, 4f, 6f, 7f};

        System.out.println(Arrays.toString(arr2));

        ss.sort(arr2);

        System.out.println(Arrays.toString(arr2));

        // double

        Double[] arr3 = {2.2, 1.3, 8.4, 3.5, 5.6, 4.7, 6.8, 7.1};

        System.out.println(Arrays.toString(arr3));

        ss.sort(arr3);

        System.out.println(Arrays.toString(arr3));

        // string

        String[] arr4 = {"2.2", "1.3", "8.4", "3.5", "5.6", "4.7", "6.8", "7.1"};

        System.out.println(Arrays.toString(arr4));

        ss.sort(arr4);

        System.out.println(Arrays.toString(arr4));

        String[] arr5 = {"Z", "B", "C", "A", "E","D", "P"};

        System.out.println(Arrays.toString(arr5));

        ss.sort(arr5);

        System.out.println(Arrays.toString(arr5));

        // student

        Student[] arr6 = {new Student("A", 55),
            new Student("B", 40),
            new Student("C", 88),
            new Student("Z", 60),
            new Student("F", 99)};

        System.out.println(Arrays.toString(arr6));

        ss.sort(arr6);

        System.out.println(Arrays.toString(arr6));


    }

    @Override
    public void sort(T[] arr) {
        int n = arr.length;
        for (int i = 0; i < n; i++){
            // 寻找[i, n)区间里的最小值
            int minIndex = i;
            for(int j = i + 1; j < n; j++){
                if(arr[j].compareTo(arr[minIndex]) < 0){
                    minIndex = j;
                }
            }
            T temp = arr[i];
            arr[i] = arr[minIndex];
            arr[minIndex] = temp;
        }
    }
}
